import {login, getUserInfo} from '@/api/admin/user'

export default {
  state: {
    username: '',
    userId: '',
    avatarImgPath: '',
    token: '',
    access: '',
    hasGetInfo: false
  },
  mutations: {
    setAvatar(state, avatarPath) {
      state.avatarImgPath = avatarPath
    },
    setUserId(state, id) {
      state.userId = id
    },
    setUserName(state, name) {
      state.username = name
    },
    setAccess(state, access) {
      state.access = access
    },
    setToken(state, token) {
      state.token = token
    },
    setHasGetInfo(state, status) {
      state.hasGetInfo = status
    }
  },
  getters: {},
  actions: {
    // 登录
    handleLogin({commit}, {username, password}) {
      username = username.trim()
      return new Promise((resolve, reject) => {
        login({
          username,
          password
        }).then(res => {
          /*const data = res.data;
          commit('setToken', 'Bearer ' + data.value);*/
          commit('setToken', 'Bearer ' + res.access_token);
          resolve()
        }).catch(err => {
          reject(err)
        })
      })
    },
    // 退出登录
    handleLogOut({state, commit}) {
      return new Promise((resolve, reject) => {
        // 如果你的退出登录无需请求接口，则可以直接使用下面三行代码而无需使用logout调用接口
        commit('setToken', '');
        commit('setAccess', []);
        // 清空localStorage
        window.localStorage.clear();
        resolve()
      })
    },
    // 获取用户相关信息
    getUserInfo({state, commit}) {
      return new Promise((resolve, reject) => {
        try {
          getUserInfo().then(res => {
            const data = res.data;
            commit('setAvatar', 'https://file.iviewui.com/dist/a0e88e83800f138b94d2414621bd9704.png');
            commit('setUserName', data.nickName);
            commit('setUserId', data.userId);
            // commit('setAccess', ['super_admin', 'admin']);
            // 菜单权限和角色权限合并
            let accessArr = data.permissionSet.concat(data.grantedAuthoritySet);
            commit('setAccess', accessArr);
            commit('setHasGetInfo', true);
            resolve(data)
          }).catch(err => {
            reject(err)
          })
        } catch (error) {
          reject(error)
        }
      })
    }
  }
}
